<?php

namespace app\admin\controller;

use app\admin\model\User as ModelUser;
use app\admin\validate\User as ValidateUser;
use app\api\validate\User as ApiValidateUser;
use app\common\LogService;
use think\exception\ValidateException;
use think\facade\Db;

class User extends Base
{
    public function index()
    {
        $userNoExamine = ModelUser::where(['status' => 0])->count();
        return view('index', ['userNoExamine' => $userNoExamine]);
    }
    public function list()
    {
        $limit = input('limit');
        $id = input('id');
        $qq = input('qq');
        $nickname = input('nickname');
        $list = ModelUser::order('id desc');
        if (!empty($id)) {
            $list->where(['id' => $id]);
        }
        if (!empty($qq)) {
            $list->where('qq', 'like', "%$qq%");
        }
        if (!empty($nickname)) {
            $list->where('nickname', 'like', "%$nickname%");
        }

        $list = $list->paginate($limit);
        return success($list);
    }
    public function add()
    {
        return view();
    }
    public function doAdd()
    {
        $param = input('post.');
        $user_id = $this->uid;
        $recordLog = function ($status, $message) use ($user_id) {
            LogService::record(
                name: '添加用户',
                user_id: $user_id,
                content: ['reason' => $message],
                user_type: 2

            );
        };
        try {
            validate(ApiValidateUser::class)->check($param);
            $user = ModelUser::where('qq', $param['qq']);
            if (!$user->findOrEmpty()->isEmpty()) {
                $recordLog(0, '已存在该QQ，请更换其他的');
                return error('已存在该QQ，请更换其他的');
            }
            $data = [
                'qq' => $param['qq'],
                'nickname' => $param['nickname'] ?: 'gn_' . randStr(5) . substr(time(), 5, 5),
                'password' => md5($param['password'] . config('secure.secure_salt')),
                'reg_ip' => getIP()
            ];
            $res = ModelUser::create($data);
            if ($res) return success();
            return error();
        } catch (ValidateException $e) {
            return error($e->getMessage(),  201, '',);
        }
    }
    public function edit($id)
    {
        $user = ModelUser::where(['id' => $id])->find();
        return view('edit', ['data' => $user]);
    }
    public function doEdit()
    {
        $param = input('post.');
        $user_id = $this->uid;
        $target_id = isset($param['id']) ? $param['id'] : 0;
        $recordLog = function ($status, $message) use ($user_id, $target_id) {
            LogService::record(
                name: '编辑用户',
                user_id: $user_id,
                target_id: $target_id,
                status: $status,
                content: ['reason' => $message],
                user_type: 2

            );
        };
        try {
            validate(ValidateUser::class)->check($param);
            $user = ModelUser::where(['id' => $param['id']])->find();
            if (!$user) {
                $recordLog(0, '用户不存在');
                return error('用户不存在');
            }
            if (isset($param['qq']) && $param['qq'] != $user['qq']) {
                $hasQQ = Db::name('user')->where(['qq' => $param['qq']])->find();
                if ($hasQQ) {
                    $recordLog(0, '已存在该QQ');
                    return error('已存在该QQ');
                }
            }
            if (isset($param['nickname'])  && $param['nickname'] != $user['nickname']) {
                $hasQQ = Db::name('user')->where(['nickname' => $param['nickname']])->find();
                if ($hasQQ) {
                    $recordLog(0, '已存在该昵称');
                    return error('已存在该昵称');
                }
            }
            if (!empty($param['password'])) {
                $param['password'] = md5($param['password'] .  config('secure.secure_salt'));
            } else {
                unset($param['password']);
            }
            if (!empty($param['vip_time'])) {
                $param['vip_time'] =  strtotime($param['vip_time']);
            }
            $res = ModelUser::where(['id' => $param['id']])->update($param);
            if ($res) {
                $recordLog(1, '');
                return success();
            }
            $recordLog(0, '更新失败，无数据变化');
            return error('更新失败，无数据变化');
        } catch (ValidateException $e) {
            $recordLog(0, $e->getError());
            return error($e->getError());
        }
    }
    public function del($id)
    {
        $ids = explode(',', $id);
        $res = ModelUser::destroy($ids);
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '批量删除用户',
                user_id: $this->uid,
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }

    // 一键审核
    public function examineAll()
    {
        $type = input('type', 1);

        if ($type == 1) {
            $res = ModelUser::where(['status' => 0])->update(['status' => 1]);
            $target_id =  ModelUser::where(['status' => 0])->column('id');
            $id = implode(',', $target_id);
            $log_name = '一键审核用户';
        } else {
            $id = input('id');
            $ids = explode(',', $id);
            $res = ModelUser::whereIn('id', $ids)->update(['status' => 1]);
            $log_name = '批量审核用户';
        }
        $recordLog = function ($status, $message = '') use ($log_name, $id) {
            LogService::record(
                name: $log_name,
                user_id: $this->uid,
                target_id: $id,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }
    // 头像上传
    public function uploadAvator()
    {
        $file =  request()->file();
        try {
            validate(['avator' => 'fileSize:5242880|fileExt:jpg,png,jpeg'])
                ->check($file);
            if (empty($file)) return error();
            $has = Db::name('avator')->where(['user_id' => $this->uid])->find();
            $avator = \think\facade\Filesystem::disk('images')->putFile('avator', $file['avator']);
            if (!$avator) return error('头像上传失败');
            $avator = '/static/images/' . str_replace('\\', '/', $avator);
            if ($has) {
                @unlink(app()->getRootPath() . '/public' . $has['avator']);
                $res = Db::name('avator')->where(['user_id' => $this->uid])->update(['avator' => $avator, 'create_time' => time()]);
            } else {
                $res = Db::name('avator')->insert(['user_id' => $this->uid, 'avator' => $avator, 'create_time' => time()]);
            }
            LogService::record(
                user_id: $this->uid,
                name: '上传用户头像',
                user_type: 2,
            );
            if ($res) return success($avator);
            return error();
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
    }
}
